package com.handu.luna.boss.controller;

import java.io.UnsupportedEncodingException;
import java.util.Base64;


import com.handu.luna.core.domain.promotion.CreditPromotion;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import com.handu.luna.core.domain.goods.Goods;
import com.handu.luna.core.domain.promotion.CreditPromotionGoods;
import com.handu.luna.core.domain.searchVo.GoodsSearch;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Controller
@RequestMapping("/promotion/creditpromotiongoods/*")
public class CreditPromotionGoodsController extends BaseController {

	@RequestMapping(value = { "index/{creditPromotionId}" })
	public BossModel index(@PathVariable long creditPromotionId, @PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) {

        CreditPromotion creditPromotion = context.getCreditPromotionRepository().findOne(creditPromotionId);

		return createModel("promotion/creditpromotiongoods/index")
				.add("creditpromotiongoodsPage", context.getCreditPromotionGoodsRepository().findByCreditPromotionId(creditPromotionId, pageable))
                .add("viewState", "")
				.add("creditPromotionId", creditPromotionId)
                .add("creditPromotion",creditPromotion);


	}

	@RequestMapping(value = "add/{creditPromotionId}")
	public BossModel add(@PathVariable long creditPromotionId) {

        CreditPromotion creditPromotion = context.getCreditPromotionRepository().findOne(creditPromotionId);

		return createModel("promotion/creditpromotiongoods/add_info")
				.add("goodsSearch", new GoodsSearch())
				.add("creditPromotionId", creditPromotionId)
                .add("creditPromotion",creditPromotion)
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", context.getCategoryRepository().findAll());
	}

	@RequestMapping(value = "edit/{creditPromotionId}/{id}")
	public BossModel add(@PathVariable long creditPromotionId, @PathVariable long id) {

        CreditPromotion creditPromotion = context.getCreditPromotionRepository().findOne(creditPromotionId);

		return createModel("promotion/creditpromotiongoods/edit")
                .add("spg", context.getCreditPromotionGoodsRepository().findOne(id))
                .add("creditPromotionId", creditPromotionId)
                .add("creditPromotion",creditPromotion);
	}

	@RequestMapping(value = "list/{creditPromotionId}", method = RequestMethod.POST)
	public BossModel list(GoodsSearch goodsSearch, @PathVariable long creditPromotionId, @PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) throws UnsupportedEncodingException {

		Page<Goods> goodsList = context.getGoodsRepository().findAll(Goods.topicSearchGoods(goodsSearch), pageable);
		for (Goods good : goodsList) {
			CreditPromotionGoods creditPromotionGoods = context.getCreditPromotionGoodsRepository().findByCreditPromotionIdAndGoodsId(creditPromotionId, good.getId());
            if (creditPromotionGoods != null) {
                good.setCreditPromotionGoods(creditPromotionGoods);
            }
		}

        CreditPromotion creditPromotion = context.getCreditPromotionRepository().findOne(creditPromotionId);
		return createModel("promotion/creditpromotiongoods/info")
				.add("goodsPage", goodsList)
				.add("goodsSearch", goodsSearch)
				.add("creditPromotionId", creditPromotionId)
                .add("creditPromotion",creditPromotion)
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", context.getCategoryRepository().findAll())
				.add("viewState", Base64.getEncoder().encodeToString(JSONObject.fromObject(goodsSearch).toString().getBytes("UTF-8")));
	}

	@RequestMapping(value = "list/{creditPromotionId}", method = RequestMethod.GET)
	public BossModel list(String viewState, @PathVariable long creditPromotionId, @PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) throws UnsupportedEncodingException {

		GoodsSearch search;
		if (viewState != null && !viewState.trim().equals("")) {
			search = (GoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), GoodsSearch.class);
		} else {
			search = new GoodsSearch();
		}
        CreditPromotion creditPromotion = context.getCreditPromotionRepository().findOne(creditPromotionId);
		Page<Goods> goodsList = context.getGoodsRepository().findAll(new Goods().selectCondition(search), pageable);
		for (Goods good : goodsList) {
			CreditPromotionGoods creditPromotionGoods = context.getCreditPromotionGoodsRepository().findByCreditPromotionIdAndGoodsId(creditPromotionId, good.getId());
            if (creditPromotionGoods != null) {
                good.setCreditPromotionGoods(creditPromotionGoods);
            }
		}
		return createModel("promotion/creditpromotiongoods/info")
				.add("goodsPage", goodsList).add("goodsSearch", search)
				.add("creditPromotionId", creditPromotionId)
                .add("creditPromotion", creditPromotion)
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", context.getCategoryRepository().findAll())
				.add("viewState", viewState == null ? "" : viewState);
	}

	@RequestMapping(value = "save/{creditPromotionId}", method = RequestMethod.POST)
    @InitBinder(value = {"multiple","credit"})
	public BossModel save(@Valid @ModelAttribute("spg") final CreditPromotionGoods spg, @PathVariable long creditPromotionId, final BindingResult bindingResult, RedirectAttributes redirectAttributes,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) {

        CreditPromotion creditPromotion = context.getCreditPromotionRepository().findOne(creditPromotionId);

		if (bindingResult.hasErrors()) {
			return createModel("promotion/creditpromotiongoods/edit")
                    .add("spg", context.getCreditPromotionGoodsRepository().findOne(spg.getId()))
                    .add("creditPromotionId", creditPromotionId)
                    .add("creditPromotion", creditPromotion);
		}
		String messagePrefix = spg.getSucessFlashMessage("");
		context.getCreditPromotionGoodsRepository().save(spg);
		return createModel("promotion/creditpromotiongoods/index")
                .add("creditpromotiongoodsPage", context.getCreditPromotionGoodsRepository().findByCreditPromotionId(creditPromotionId, pageable))
                .add("viewState", "")
				.add("creditPromotionId", creditPromotionId)
                .add("creditPromotion", creditPromotion)
				.add("message", messagePrefix);
	}

	@RequestMapping(value = "ajaxSave", method = RequestMethod.POST)
	public BossModel save(long ajaxId, Integer ajaxMultiple, Integer ajaxCredit, long ajaxCreditPromotionId, String viewState, @PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) throws UnsupportedEncodingException {

        CreditPromotion creditPromotion = context.getCreditPromotionRepository().findOne(ajaxCreditPromotionId);

        CreditPromotionGoods creditPromotionGoods = new CreditPromotionGoods();
        creditPromotionGoods.setCreditPromotionId(ajaxCreditPromotionId);
        creditPromotionGoods.setGoodsId(ajaxId);
        if(creditPromotion.getCreditType() == CreditPromotion.CreditType.CREDIT  && ajaxCredit != null) {
            creditPromotionGoods.setCredit(ajaxCredit);
        }else if(creditPromotion.getCreditType() == CreditPromotion.CreditType.MULTIPLE && ajaxMultiple != null) {
            creditPromotionGoods.setMultiple(ajaxMultiple);
        }
        context.getCreditPromotionGoodsRepository().save(creditPromotionGoods);

		GoodsSearch search;
		if (viewState != null && !viewState.trim().equals("")) {
			search = (GoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), GoodsSearch.class);
		} else {
			search = new GoodsSearch();
		}


		Page<Goods> goodsList = context.getGoodsRepository().findAll(Goods.topicSearchGoods(search), pageable);
		for (Goods good : goodsList) {
			CreditPromotionGoods creditPromotionGoods2= context.getCreditPromotionGoodsRepository().findByCreditPromotionIdAndGoodsId(ajaxCreditPromotionId, good.getId());
            if (creditPromotionGoods2 != null) {
                good.setCreditPromotionGoods(creditPromotionGoods2);
            }
		}
		return createModel("promotion/creditpromotiongoods/goods_table")
				.add("goodsPage", goodsList)
                .add("goodsSearch", search)
				.add("creditPromotionId", ajaxCreditPromotionId)
                .add("creditPromotion",creditPromotion)
                .add("viewState", viewState);
	}

	@RequestMapping(value = "delete", method = RequestMethod.POST)
	public BossModel delete(long id, long spid, @PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) {

         CreditPromotion creditPromotion = context.getCreditPromotionRepository().findOne(spid);

		context.getCreditPromotionGoodsRepository().delete(id);
		return createModel("promotion/creditpromotiongoods/creditpromotiongoods_table")
				.add("creditpromotiongoodsPage", context.getCreditPromotionGoodsRepository().findByCreditPromotionId(spid, pageable))
				.add("viewState", "")
                .add("creditPromotionId", spid)
                .add("creditPromotion",creditPromotion);
	}

    @RequestMapping(value = "ajaxDelete", method = RequestMethod.POST)
	public BossModel delete(long goodsId,long creditPromotionId,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable,String viewState) throws UnsupportedEncodingException {

        CreditPromotionGoods creditPromotionGoods = context.getCreditPromotionGoodsRepository().findByCreditPromotionIdAndGoodsId(creditPromotionId,goodsId);

        context.getCreditPromotionGoodsRepository().delete(creditPromotionGoods);

		GoodsSearch search;
		if (StringUtils.isNotBlank(viewState)) {
			search = (GoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), GoodsSearch.class);
        } else {
			search = new GoodsSearch();
		}

		Page<Goods> goodsList = context.getGoodsRepository().findAll(Goods.topicSearchGoods(search), pageable);
		for (Goods good : goodsList) {
			CreditPromotionGoods creditPromotionGoods1 = context.getCreditPromotionGoodsRepository().findByCreditPromotionIdAndGoodsId(creditPromotionId, good.getId());
            if (creditPromotionGoods1 != null) {
				 good.setCreditPromotionGoods(creditPromotionGoods1);
			}
		}

       CreditPromotion creditPromotion = context.getCreditPromotionRepository().findOne(creditPromotionId);
		return createModel("promotion/creditpromotiongoods/goods_table")
				.add("goodsPage", goodsList)
                .add("goodsSearch", search)
                .add("creditPromotionId", creditPromotionId)
                .add("creditPromotion",creditPromotion)
                .add("viewState", viewState);
	}
}
